/**
 * 用于table操作项内容
 * 1. 自动增加分隔条
 * 2. 超出阈值自动切割滑动显示
 */

import cs from 'classnames';
import React, { useMemo } from 'react';

import { Divider } from 'antd';

import './index.less';
import { TableDropdown } from '@ant-design/pro-components';

export interface ActionProps
  extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
  /** 最多显示多少个功能,多余的下拉选择 */
  limit?: number;
}

const Action: React.FC<ActionProps> = ({ limit, className, children, ...rest }) => {
  const render = useMemo(() => {
    const listChildren = React.Children.toArray(children).filter(Boolean);

    if (typeof limit === 'number' && listChildren.length > limit) {
      const before = listChildren.slice(0, limit);
      const after = listChildren.slice(limit);

      return (
        <>
          {before.map((item, index) => {
            return (
              <div className="action-item" key={index}>
                {item}

                <Divider type="vertical" />
              </div>
            );
          })}

          <TableDropdown
            menus={after.map((item, index) => ({
              key: String(index),
              name: item,
            }))}
          />
        </>
      );
    }

    return listChildren.map((item, index) => {
      return (
        <div className="action-item" key={index}>
          {index > 0 && <Divider type="vertical" />}

          {item}
        </div>
      );
    });
  }, [children, limit]);

  return (
    <div className={cs('action', className)} {...rest}>
      {render}
    </div>
  );
};

export default Action;
